package com.tevintao.marketingsystem.activity;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tevintao.marketingsystem.R;
import com.tevintao.marketingsystem.services.AccountManager;
import com.tevintao.marketingsystem.tool.PhoneTool;
import com.tevintao.marketingsystem.tool.SystemPathTool;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Random;

public class ActReportDeviceInfo extends AppCompatActivity implements View.OnClickListener {

    private Button mCrete, mReport, mWriteLocal;

    private EditText mPhoneEdit;
    private TextView mContext;

    private RequestQueue queue = null;
    private StringRequest mSwitchAccountRequest;

    private HashMap<String, String> mHeader = new HashMap<>();
    private Random r = new Random();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_account_manager);

        mCrete = (Button) findViewById(R.id.act_report_create);
        mReport = (Button) findViewById(R.id.act_report_report);
        mWriteLocal = (Button) findViewById(R.id.act_report_write_local);
        mCrete.setOnClickListener(this);
        mReport.setOnClickListener(this);
        mWriteLocal.setOnClickListener(this);

        mPhoneEdit = (EditText) findViewById(R.id.act_account_phone);
        mContext = (TextView) findViewById(R.id.act_report_context);
        queue = Volley.newRequestQueue(this);
        new Thread(mGetDeviceName).start();
    }

    private String deviceName;
    private Handler handler = new Handler();

    private String getEditPhone() {
        String phone = mPhoneEdit.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(ActReportDeviceInfo.this, "没有电话号码，请点击获取，得到号码，+86字符不用处理", Toast.LENGTH_LONG).show();
            return null;
        }

        phone = phone.replace(" ", "");
        if (phone.startsWith("+86")) {
            phone = phone.replace("+86", "");
        }
        return phone;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.act_report_create:
                break;
            case R.id.act_account_create:
                break;
            case R.id.act_report_write_local:
                break;
        }
    }

    /**
     * 检查环境，如果环境不符合条件，不让生成信息
     * 1，wifi连接
     * 2，蓝牙连接
     * 3，
     *
     * @return
     */
    private boolean checkEnvir() {
        ConnectivityManager connManager = (ConnectivityManager) this
                .getSystemService(CONNECTIVITY_SERVICE);
        // 获取代表联网状态的NetWorkInfo对象
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        // 获取当前的网络连接是否可用
        boolean available = networkInfo.isAvailable();
        if (!available) {
            showToast("通知 当前无可用的网络连接 ,至少保证存在手机网络连接");
            return false;
        }

        NetworkInfo.State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
        if (NetworkInfo.State.CONNECTED != state) {
            showToast("当前没有移动网络,请确认插卡。");
            return false;
        }

        state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
        if (NetworkInfo.State.CONNECTED != state) {
            showToast("请打开wifi");
            startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
            return false;
        }
        return true;
    }

    private void createDeviceInfo() {
        if (!checkEnvir()) {
            return;
        }
        mHeader.clear();

        StringBuilder sb = new StringBuilder();
        WifiManager wifi = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

        WifiInfo info = wifi.getConnectionInfo();

//        String SERIAL = Build.SERIAL;
        long v = r.nextLong();
        String ss = Long.toHexString(v).toUpperCase();
        sb.append(" SERIAL = ");
        sb.append(ss);
        sb.append("\n");
        mHeader.put("SERIAL", ss);

        String mac = info.getMacAddress();
        String rMac = PhoneTool.getRandomMac(mac);
        sb.append(" mac = ");
        sb.append(rMac);
        sb.append("\n");
        mHeader.put("MAC", rMac);

        String bssid = info.getBSSID();
        String bMac = PhoneTool.getRandomMac(bssid);
        sb.append(" bssid = ");
        sb.append(bMac);
        sb.append("\n");
        mHeader.put("BSSID", bMac);

//        String androidId = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        v = r.nextLong();
        String aid = Long.toHexString(v);
        sb.append(" androidId = ");
        sb.append(aid);
        sb.append("\n");
        mHeader.put("ANDROIDID", aid);


        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        String phoneNum = "";
//        String phoneNum = telephonyManager.getLine1Number();
        if (TextUtils.isEmpty(phoneNum)) {
            if (!TextUtils.isEmpty(mPhoneEdit.getText())) {
                phoneNum = mPhoneEdit.getText().toString();
            }
        }
        sb.append(" phoneNum = ");
        sb.append(phoneNum);
        sb.append("\n");
        mHeader.put("PhoneNumber", phoneNum);


        String imei = telephonyManager.getDeviceId();
        sb.append(" imei = ");
        sb.append(imei);
        sb.append("\n");
        mHeader.put("getDeviceId", imei);


        String getNetworkCountryIso = telephonyManager.getNetworkCountryIso();
        sb.append(" getNetworkCountryIso = ");
        sb.append(getNetworkCountryIso);
        sb.append("\n");
        mHeader.put("getNetworkCountryIso", getNetworkCountryIso);

        String getNetworkOperator = telephonyManager.getNetworkOperator();
        sb.append(" getNetworkOperator = ");
        sb.append(getNetworkOperator);
        sb.append("\n");
        mHeader.put("getNetworkOperator", getNetworkOperator);

        if (!TextUtils.isEmpty(getNetworkOperator)) {
            mHeader.put("MCC", getNetworkOperator.substring(0, 3));
            mHeader.put("MNC", getNetworkOperator.substring(3, 5));
        }

        String getNetworkOperatorName = telephonyManager.getNetworkOperatorName();
        String uname = "";
        try {
            uname = URLEncoder.encode(getNetworkOperatorName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        sb.append(" getNetworkOperatorName = ");
        sb.append(getNetworkOperatorName);
        sb.append("\n");
        mHeader.put("getNetworkOperatorName", uname);

        String getSimCountryIso = telephonyManager.getSimCountryIso();
        sb.append(" getSimCountryIso = ");
        sb.append(getSimCountryIso);
        sb.append("\n");
        mHeader.put("getSimCountryIso", getSimCountryIso);

        String getSimOperator = telephonyManager.getSimOperator();
        sb.append(" getSimOperator = ");
        sb.append(getSimOperator);
        sb.append("\n");
        mHeader.put("getSimOperator", getSimOperator);

        String getSimOperatorName = telephonyManager.getSimOperatorName();
        sb.append(" getSimOperatorName = ");
        sb.append(getSimOperatorName);
        sb.append("\n");

        String simOperatorName = "";
        try {
            simOperatorName = URLEncoder.encode(getSimOperatorName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        mHeader.put("getSimOperatorName", simOperatorName);

        String getSimSerialNumber = telephonyManager.getSimSerialNumber();
        sb.append(" getSimSerialNumber = ");
        sb.append(getSimSerialNumber);
        sb.append("\n");
        mHeader.put("getSimSerialNumber", getSimSerialNumber);

        String getSubscriberId = telephonyManager.getSubscriberId();
        sb.append(" getSubscriberId = ");
        sb.append(getSubscriberId);
        sb.append("\n");
        mHeader.put("getSubscriberId", getSubscriberId);

        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if (adapter == null) {
//            showToast("蓝牙未连接");
        } else {
            String bmac = PhoneTool.getRandomMac(adapter.getAddress());
            sb.append("BTMAC = " + bmac);
            mHeader.put("BTMAC", bmac);
        }

        mContext.setText(sb.toString());
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    private Runnable mGetDeviceName = new Runnable() {
        @Override
        public void run() {
            if (!SystemPathTool.exitPath(AccountManager.SD_MS_ROOT)) {
                SystemPathTool.mkDir(AccountManager.SD_MS_ROOT);
            }
            if (SystemPathTool.exitFile(ActSetDevice.device_name_file)) {
                deviceName = SystemPathTool.getOutPutContent(ActSetDevice.device_name_file);
                if (TextUtils.isEmpty(deviceName)) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ActReportDeviceInfo.this.startActivity(new Intent(ActReportDeviceInfo.this, ActSetDevice.class));
                        }
                    });
                } else {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            ActReportDeviceInfo.this.setTitle("设备名称为  " + deviceName);
                        }
                    });
                }
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        ActReportDeviceInfo.this.startActivity(new Intent(ActReportDeviceInfo.this, ActSetDevice.class));
                    }
                });
            }
        }
    };

}
